<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta content="yes" name="apple-mobile-web-app-capable">
  <meta content="yes" name="apple-touch-fullscreen">
  <meta content="telephone=no,email=no" name="format-detection">
  <title>业绩走势（带交易）</title>
  <link rel="stylesheet" href="../css/fund.css" />
  <style>
    canvas {
      height: 46.4vw;
    }
    #dealMoney {
      display: none;
    }

    .tooltip-title {
      line-height: 4vw;
    }

    @media only screen and (orientation: landscape) {
      .chart-card {
        margin: 0;
      }
      .chart-card-title {
        padding: 0 2.9985vw;
        width: 100%;
        height: 12vh;
        box-shadow: 0 1px 0 0 #E8E8E8;
        color: rgba(0, 0, 0, .85);
        font-size: 4.26667vh;
        line-height: 12vh;
        vertical-align: middle;
      }
      .chart-legend {
        position: relative;
        height: 6.667vh;
        padding: 0 2.9985vw;
        line-height: 6.667vh;
        flex-direction: row-reverse;
        box-shadow: 0 1px 0 0 #E8E8E8;
        font-size: 3.2vh;
      }
      .item {
        width: auto;
        margin-left: 1.7991004497751124vw;
      }
      .chart-legend-title {
        position: absolute;
        display: inline-block;
        left: 2.9985vw;
        color: #2e2e2e;
        top: 1px;
      }
      .tooltip-wrapper {
        height: 6.667vh;
        padding: 0 2.9985vw;
        line-height: 6.667vh;
      }
      .tooltip-content {
        font-size: 3.2vh;
        flex-direction: row-reverse;
      }
      .tooltip-title {
        position: absolute;
        display: inline-block;
        left: 2.9985vw;
        color: #2e2e2e;
        top: 1px;
        margin: 0;
        line-height: 6.667vh;
        font-size: 3.2vh;
      }

      #dealMoney {
        display: inline;
        width: auto;
      }
      canvas {
        width: 100%;
        height: 70.6667vh;
        display: block;
      }
      .chart-card-footer {
        width: 100%;
        height: 10.667vh;
        line-height: 10.667vh;
      }

      .item span.item-marker {
        width: 0.8995502248875562vw;
        height: 0.5333333333333333vh;
      }

      .item span.item-marker-point {
        width: 5px;
        height: 5px;
      }

      .item:nth-child(1) {
        order: 5;
      }
      .item:nth-child(2) {
        order: 4;
      }
      .item:nth-child(3) {
        order: 3;
      }
      .item:nth-child(4) {
        order: 2;
      }
      .item:nth-child(5) {
        order: 1;
      }

      .tab {
        height: 10.667vh;
        line-height: 10.667vh;
      }

      .tab .time-button {
        font-size: 3.4667vh;
        height: 10.667vh;
        line-height: 10.667vh;
      }
    }

  </style>
  <script src="../js/f2-all.min.js"></script>
  <script src="https://gw.alipayobjects.com/os/antv/assets/lib/jquery-3.2.1.min.js"></script>
  <script src="../js/util.js"></script>
</head>

<body>
  <div class="chart-card">
    <div class="chart-card-title">
      业绩走势
    </div>
    <div class="chart-container">
      <div class="tooltip-wrapper">
        <div class="tooltip-title" id="tooltipTitle"></div>
        <div class="tooltip-content" id="tooltip">
          <div class="item" id="dealMoney">
          </div>
          <div class="item">
            <span class="item-marker" style="background: #1890ff"></span>
            <span>本基金:</span>
            <span class="item-value" data-type="本基金">--</span>
          </div>
          <div class="item">
            <span class="item-marker" style="background: #5CDBD3"></span>
            <span>同类均值:</span>
            <span class="item-value" data-type="同类平均">--</span>
          </div>
          <div class="item" style="padding-right: 0;">
            <span class="item-marker" style="background: #B37FEB"></span>
            <span>沪深300:</span>
            <span class="item-value" data-type="沪深300">--</span>
          </div>
        </div>
      </div>
      <!-- 自定义 html 图表图例 -->
      <div class="chart-legend" id="chartLegend">
        <div class="chart-legend-title"></div>
        <div class="item">
          <span class="item-marker" style="background: #1890ff"></span>
          <span>本基金:</span>
          <span class="item-value" data-type="本基金">--</span>
        </div>
        <div class="item">
          <span class="item-marker" style="background: #5CDBD3"></span>
          <span>同类均值:</span>
          <span class="item-value" data-type="同类平均">--</span>
        </div>
        <div class="item">
          <span class="item-marker" style="background: #B37FEB"></span>
          <span>沪深300:</span>
          <span class="item-value" data-type="沪深300">--</span>
        </div>
        <div class="item">
          <span class="item-marker-point" style="background: #FA8C16"></span>
          <span>买入点</span>
        </div>
        <div class="item" style="padding-right: 0;">
          <span class="item-marker-point" style="background: #1890FF"></span>
          <span>卖出点</span>
        </div>
      </div>
      <!-- 图表主题 -->
      <canvas id="mountNode"></canvas>
      <!-- 时间切换 按钮 -->
      <div class="tab">
        <button class="time-button button-20 active" id="one-month">近 1 月</button>
        <button class="time-button button-20" id="three-month">近 3 月</button>
        <button class="time-button button-20" id="six-month">近 6 月</button>
        <button class="time-button button-20" id="one-year">近 1 年</button>
        <button class="time-button button-20" id="three-year">近 3 年</button>
      </div>
    </div>
  </div>
  <script>
    var Animate = F2.Animate;
    var Util = F2.Util;
    var Chart = F2.Chart;
    // 自定义线图变更动画
    Animate.registerAnimation('lineUpdate', function(updateShape, animateCfg) {
      var cacheShape = updateShape.get('cacheShape'); // 该动画 shape 的前一个状态
      var cacheAttrs = cacheShape.attrs; // 上一个 shape 属性
      // var geomType = cacheShape.geomType; // 图形类型

      var oldPoints = cacheAttrs.points; // 上一个状态的关键点
      var newPoints = updateShape.attr('points'); // 当前 shape 的关键点

      var oldLength = oldPoints.length;
      var newLength = newPoints.length;
      // var deltaLength = (geomType === 'area') ? (oldLength - newLength) / 2 : (oldLength - newLength);
      var deltaLength = oldLength - newLength;

      if (deltaLength > 0 ) {
        var firstPoint = newPoints[0];
        var lastPoint = newPoints[newPoints.length - 1];

        for (var i =0; i< deltaLength; i++) {
          newPoints.splice(0, 0, firstPoint);
        }
      } else {
        deltaLength = Math.abs(deltaLength);
        var firstPoint1 = oldPoints[0];
        var lastPoint1 = oldPoints[oldPoints.length - 1];

        for (var k =0; k < deltaLength; k++) {
          oldPoints.splice(0, 0, firstPoint1);
        }
        cacheAttrs.points = oldPoints;
      }
      updateShape.attr(cacheAttrs);
      updateShape.animate().to(Util.mix({
        attrs: {
          points: newPoints
        }
      }, animateCfg));
    });
    Animate.registerAnimation('pointZoom', function (shape, animateCfg) {
      var r = shape.attr('r');
      shape.attr('r', 0);
      shape.animate().to(Util.mix({
        attrs: {
          r
        }
      }, animateCfg));
    });
    // 给数据打标，标记存在交易行为的数据，tag: 0 表示不存在交易，tag: 1 表示买入，tag: 2 表示卖出
    function mockData(data) {
      var buyDates = [ '2018-03-23', '2018-04-03', '2018-04-26', '2018-05-02'  ];
      var sellDates = [ '2018-05-07', '2018-05-10', '2018-05-15' ];

      data.forEach(function(item) {
        var date = item.reportDate;
        var name = item.name;
        if (name === '本基金') {
          if (buyDates.indexOf(date) !== -1) {
            item.tag = 1;
            item.deal = 1000;
          } else if (sellDates.indexOf(date) !== -1) {
            item.tag = 2;
            item.deal = 1000;
          } else {
            item.tag = 0;
          }
        }
      });

      return data;
    }

    var colorMap = {
      '本基金': '#1890FF',
      '沪深300': 'rgba(92, 219, 211, 0.5)',
      '同类平均': 'rgba(179, 127, 235, 0.5)'
    };
    var sizeMap = {
      '本基金': 2,
      '沪深300': 1,
      '同类平均': 1
    };
    var tagImageMap = {
      1: 'https://gw.alipayobjects.com/zos/rmsportal/ueFdchLiHajoHkuQIslH.png',
      2: 'https://gw.alipayobjects.com/zos/rmsportal/LnOYhcIVlbunHkgpoCLB.png'
    };

    // 昨天的收益率，用于图例的绘制，无论时间切换维度多少，默认都会显示昨天的收益率
    var yesterdayRates = {
      '本基金': 14.12,
      '沪深300': 3.71,
      '同类平均': 3.54
    };

    var RANGE = {
      'one-year': {
        rangeMin: {
          x: '2017-05-22'
        },
        rangeMax: {
          x: '2018-05-22'
        }
      },
      'three-year': {
        rangeMax: {
          x: '2018-05-22'
        },
        rangeMin: {
          x: '2016-09-29'
        }
      }
    };

    var yesterday = '2018-05-22（昨日）';
    // 图表绘制完成之后绘制图例
    $('#chartLegend .chart-legend-title').text(yesterday);
    $('#chartLegend .item-value').each(function(index, ele) {
      var type = $(ele).data('type');
      let value = yesterdayRates[type];
      let color;
      if (value > 0) {
        value = '+' + value;
        color = '#F5222D';
      }
      if (value < 0) {
        color = '#53BC20';
      }
      $(ele).css({
        color: color
      });
      $(ele).text(value + '%');
    });

    var landscape = window.innerWidth > window.innerHeight ? true : false;
    var xTickCount = landscape ? 5 : 3;

    var chart = new Chart({
      id: 'mountNode',
      pixelRatio: window.devicePixelRatio,
      padding: [ 14, 'auto', 'auto' ]
    });

    var reportDateDef = {
      type: 'timeCat',
      tickCount: xTickCount,
      range: [ 0, 1 ],
      mask: 'YYYY-MM-DD'
    };

    // 处理数据
    $.getJSON('./data/performance/one-month.json', function(json) {
      json = mockData(json);
      chart.source(json, {
        rate: {
          tickCount: 5
        },
        name: {
          values: [ '沪深300', '同类平均', '本基金' ]
        }
      });
      chart.scale('reportDate', reportDateDef);
      chart.animate({
        'axis-label': false
      });
      chart.axis('reportDate', {
        line: null,
        label: function(text, index, total) {
          var cfg = {
            textAlign: 'center'
          };
          if (index === 0) {
            cfg.textAlign = 'start';
          } else if (index === (total - 1)) {
            cfg.textAlign = 'end';
          }

          var arr = text.split('-');
          if (arr[0] === '2018') {
            cfg.text = arr[1] + '-' + arr[2];
          }
          return cfg;
        }
      });
      chart.axis('rate', {
        label: function(text) {
          text = text * 1;
          var cfg = {
            text: text.toFixed(2) + '%'
          };
          if (text > 0) {
            cfg.text = '+' + cfg.text;
          } else if (text === 0) {
            cfg.fill = '#000';
            cfg.fontWeight = 'bold';
          }
          return cfg;
        },
        grid: function(text, index) {
          if (text == 0) {
            return {
              lineDash: null
            };
          }
        }
      });
      chart.legend(false); // 不使用默认图例
      chart.tooltip({
        showCrosshairs: true,
        crosshairsStyle: {
          stroke: '#CAD7EF'
        },
        custom: true,
        onChange: function(obj) {
          var items = obj.items;
          var title = items[0].origin.reportDate;
          var rates = {};
          let tag;
          let dealMoney;
          items.forEach(function(item) {
            rates[item.name] = item.value * 1;
            if (item.origin.tag) {
              tag = item.origin.tag;
              dealMoney = item.origin.deal;
            }
          });

          let titleContent;
          if (tag) { // 用户有交易操作
            titleContent = title + '<img src="' + tagImageMap[tag] + '" style="width: 27.5px;height: 15px;margin-left: 8px;" />';
            var dealInfo = (tag === 1 ? '买入: ' : '卖出: ') + dealMoney + '元';
            $('#dealMoney').html(dealInfo);
          } else {
            titleContent = title;
            $('#dealMoney').html('');
          }

          $('#tooltipTitle').html(titleContent);

          $('#tooltip .item-value').each(function(index, ele) {
            var type = $(ele).data('type');
            let value = rates[type];
            let color;
            if (value > 0) {
              value = '+' + value;
              color = '#F5222D';
            } else if (value < 0) {
              color = '#53BC20';
            } else {
              color = '#2E2E2E';
            }
            $(ele).css({
              color: color
            });
            $(ele).text(value + '%');
          });

          $('.tooltip-wrapper').css('visibility', 'visible');
        },
        onHide: function() {
          $('.tooltip-wrapper').css('visibility', 'hidden');
        }
      });

      chart.line()
        .position('reportDate*rate')
        .color('name', function(val) {
          return colorMap[val];
        })
        .size('name', function(val)  {
          return sizeMap[val];
        })
        .animate({
          appear: {
            duration: 500,
          },
          update: {
            animation: 'lineUpdate',
            duration: 500
          }
        });
      chart.point()
        .position('reportDate*rate')
        .size('tag', function(val) {
          return val ? 3 : 0;
        })
        .style('tag', {
          fill: function(val) {
            if (val === 2) {
              return '#1890ff';
            } else if (val === 1) {
              return '#FA8C16';
            }
          },
          stroke: '#fff',
          lineWidth: 1.5
        })
        .animate({
          appear: {
            duration: 500,
          },
          enter: {
            animation: 'pointZoom',
            duration: 450,
            delay: 200
          },
          update: {
            duration: 500
          }
        });
      chart.render();
    });

    // button 点击操作
    $('.tab button').on('touchstart', function(e) {
      var target = $(e.target);
      var id = target.attr('id');
      if (target.hasClass('active')) {
        return;
      }

      var currentActive = $('.tab').find('button.active');
      currentActive.removeClass('active');
      target.addClass('active');

      var url = './data/performance/' + id + '.json';
      $.getJSON(url, function(json) {
        if (landscape) { // 横屏下的交互
          chart.tooltip(true);
          chart.scale('reportDate', reportDateDef);
          chart.clearInteraction(); // 先要将交互行为清楚
          if (id === 'one-year' || id === 'three-year') {
            chart.scrollBar({
              mode: 'x',
              xStyle: {
                offsetY: -4
              }
            });
            chart
            .interaction('pan', {
              mode: 'x',
              preStart: function() {
                chart.animate(false);
              },
              onEnd: function() {
                chart.animate(true);
              }
            })
            .interaction('pinch', {
              mode: 'x',
              preStart: function() {
                chart.animate(false);
              },
              onEnd: function(){
                chart.animate(true);
              }
            });
          } else {
            chart.animate(true);
            chart.scrollBar(null);
          }
        }

        json = mockData(json);
        chart.changeData(json);
      });
    });
  </script>
</body>
</html>
